package com.heima.xxljob.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/12/4
 */
@Component
public class HelloJob {
    @Value("${server.port}")
    private String port;
    @XxlJob("demoJobHandler")
    public void helloJob() {
        System.out.println("简单任务执行了。。。" + port);
    }

    /**
     * 需求：让两个节点同时执行10000个任务，每个节点分别执行5000个任务
     */
    @XxlJob("shardingJobHandler")
    public void shardingJobHandler() {
        //分片的参数
        int shardIndex = XxlJobHelper.getShardIndex();  //当前分片  0/1
        int shardTotal = XxlJobHelper.getShardTotal();  //总分片数量 2
        System.err.println("shardIndex:" + shardIndex);
        System.err.println("shardTotal:" + shardTotal);
        //业务逻辑
        //添加任务
        List<Integer> list = getList();
        for (Integer integer : list) {
            //任务编号对总分片数取模，分别交给不同分片执行
            if (integer % shardTotal == shardIndex) {
                System.out.println("当前第"+shardIndex+"分片执行了，任务项为："+integer);
            }
        }
    }
    //添加100个任务
    public List<Integer> getList(){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            list.add(i);
        }
        return list;
    }
}
